package com.example.demouploaddown;

import com.alibaba.excel.EasyExcelFactory;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * <b><code>IndexController</code></b>
 * <p>
 * Description
 * <p>
 * <b>Create Time:</b> 2021/9/8 17:10.
 *
 * @author qd.yt
 * @version 0.0.1
 * @since demo-upload-down v0.0.1
 */
@RestController
public class IndexController {

    @RequestMapping("/downExcel")
    public String downExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String fileName = "下载文档"+System.currentTimeMillis();
        // 取得输出流
        ServletOutputStream out = response.getOutputStream();
        response.reset();// 清空输出流
        response.setHeader("Content-disposition",
                // 设定输出文件头
                "attachment; filename=" + toUtf8String(fileName, request) + ".xlsx");
        // 定义输出类型
        response.setContentType("application/msexcel");
        //将数据写入输出流
        List<DataExportResultDto> list = new ArrayList<DataExportResultDto>();
        list.add(new DataExportResultDto(1,"2","3"));
        try {
            EasyExcelFactory.write(out, DataExportResultDto.class).sheet("数据").doWrite(list);

        }catch (Exception e) {
            e.printStackTrace();
        }
       out.flush();
       return "下载成功";
    }


    public static String toUtf8String(String fileName, HttpServletRequest request) throws Exception {
        final String userAgent = request.getHeader("USER-AGENT");
        String finalFileName = null;
        // IE浏览器（旧版/新版）
        if (StringUtils.contains(userAgent, "MSIE")||StringUtils.contains(userAgent, "Trident")) {
            finalFileName = URLEncoder.encode(fileName, "UTF8");
            // google,火狐浏览器
        } else if (StringUtils.contains(userAgent, "Mozilla")) {
            finalFileName = new String(fileName.getBytes(), "ISO8859-1");
        } else {
            // 其他浏览器
            finalFileName = URLEncoder.encode(fileName, "UTF8");
        }
        return finalFileName;
    }
}
